const libK = require("../lib").libKDocsDrive;
const path = require("path");
const fs = require("fs")
let kdoc = new libK.KdocsDrive('V02SM4K7yqLwAoUXAhCzMtMvNDDkGRQ00a10b3320029d3cb62');
const rs = require("randomstring");
const runParallel = require("run-parallel-limit");

kdoc.GetSpecialGroupPromise.then(async o_sg => {
  const filesize = require("filesize");
  let sg = o_sg.data.special_group;
  /**
   * @returns {Promise<{ok:Boolean,msg:String,data:{size:Number}}>}
   * @param {Number} fileid 
   */
  let real_size_of_file = (fileid) => new Promise(async resolve => {
    let get_history = await sg.getFileHistory(fileid, 0, 20);
    if (!get_history.ok) {
      return resolve({
        ok: false,
        msg: get_history.msg
      })
    }
    else {
      let hises = get_history.data.histories
      let last_ver_size = hises[hises.length - 1].fsize;
      return resolve({
        ok: true,
        msg: "ok",
        data: {
          size: last_ver_size
        }
      })
    }
  });
  /**
   * @returns {Promise<{ok:Boolean,msg:String,data:{size:Number}}>}
   * @param {Number} dirid 
   */
  let getRealSizeOfDir = (dirid) => new Promise(async resolve => {
    let sizecount = 0;
    let page = 1;

    while (true) {
      let o_list = await sg.listDownloadableItemsInFolder(dirid, (page - 1) * 20, 20, "mtime", "DESC");
      if (!o_list.ok) {
        return resolve({
          ok: false, msg: `can't get list:${o_list.msg}`
        })
      }
      let files = o_list.data.files.filter(e => e.ftype == "file");
      let dirs = o_list.data.files.filter(e => e.ftype == "folder");
      await new Promise(done => {
        runParallel(files.map(file => cb => {
          real_size_of_file(file.id).then(o => {
            if (o.ok) {
              sizecount += o.data.size;
            }
            else {
              console.log("  xxx:", file.fname, o.msg)
            }
            cb();
          })
        }), 5, () => { done() })
      });
      await new Promise(done => {
        runParallel(dirs.map(dir => cb => {
          getRealSizeOfDir(dir.id).then(o => {
            if (o.ok) {
              sizecount += o.data.size;
            } else {
              console.log("   xxx(dir)", dir.fname, o.msg)
            }
            cb();
          })
        }), 5, () => { done() })
      });
      if (o_list.data.next_offset == -1) {
        return resolve({
          ok: true,
          msg: "ok",
          data: {
            size: sizecount
          }
        })
      } else {
        console.log("dirid=", dirid, `第${page}页=`, sizecount, filesize(sizecount))
        page++;
      }
    }
  });
  let o_result = await getRealSizeOfDir(56283529888);
  console.log("KDFILE-ROOT", o_result.data.size, filesize(o_result.data.size));
})